package com.example.usagelock;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.content.Context;
import android.hardware.Camera;
import android.hardware.Camera.CameraInfo;
import android.hardware.Camera.PictureCallback;
import android.os.Environment;
import android.util.Log;

public class TakeCamera {
	static Context mContext;
	static int frontCameraId = -1;
	static Camera frontCamera;
	
	public static void Initilize(Context context){
		Log.d("CAMERA","Initilize Start");
		mContext = context;
		
		frontCameraId = FindFacingCamera();
		Log.d("CAMERA", "Camera Id : " + frontCameraId);
		CheckCameraId();
		frontCamera = Camera.open(frontCameraId);
		
		Log.d("CAMERA","Initilize End");
	}
	
	public static void TakePictureFront(){
		CheckCameraId();
		frontCamera.takePicture(null, null, new PhotoHandler(mContext));
	}
	
	public static void ReleaseCamera() {
		if (frontCamera != null) {
			frontCamera.release();
			frontCamera = null;
		}
	}
	
	private static void CheckCameraId(){
		if(frontCameraId == -1)
			throw new NullPointerException("Not found front camera!");
	}
	
	private static int FindFacingCamera(){
		int cameraNum = Camera.getNumberOfCameras();
		int result = -1;

		for(int i = 0; i < cameraNum; i++){
			CameraInfo cameraInfo = new CameraInfo();
			Camera.getCameraInfo(i, cameraInfo);
			
			if(cameraInfo.facing == CameraInfo.CAMERA_FACING_FRONT){
				result = i;
				break;
			}
		}
		
		return result;
	}
	
	private static class PhotoHandler implements PictureCallback{
		Context context;
		public PhotoHandler(Context context){
			this.context = context;
		}
		
		@Override
		public void onPictureTaken(byte[] data, Camera camera) {
			File pictureFileDir = getDir();

			if (!pictureFileDir.exists() && !pictureFileDir.mkdirs()) {
//				Toast.makeText(context, "Can't create directory to save image.",
//						Toast.LENGTH_LONG).show();
				return;

			}

			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyymmddhhmmss");
			String date = dateFormat.format(new Date());
			String photoFile = "Picture_" + date + ".jpg";

			String filename = pictureFileDir.getPath() + File.separator + photoFile;

			File pictureFile = new File(filename);

			try {
				FileOutputStream fos = new FileOutputStream(pictureFile);
				fos.write(data);
				fos.close();
//				Toast.makeText(context, "New Image saved:" + photoFile,
//						Toast.LENGTH_LONG).show();
			} catch (Exception error) {
//				Toast.makeText(context, "Image could not be saved.",
//						Toast.LENGTH_LONG).show();
			}
		}
		
		private File getDir() {
			File sdDir = Environment
					.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
			return new File(sdDir, "CameraAPIDemo");
		}
	}
}
